import angular from 'angular'
import "@yunke/jquery_pagination"
import 'angular-ui'
import {property, map, replace, cloneDeep, chain,findIndex,isEmpty} from 'lodash'
import modal from '@yunke/angular-ui/lib/yunkeModal'
import {contractType, settlementType} from '../constant'
import {isSpecial} from "../util"
import util from '@yunke/core/util';
import myMath from "../../../public/js/myservice/common/my-math";

const apiPrefix = window.G_CONFIG.api_prefix
const getData = property('data.data')
const dredgeModal = require("./dredgeModal.html")
const ENV_TEST = /test/.test(document.domain)
const JOINT_URL = ENV_TEST?'http://ck.mingyuanyun.test/#/deliveryEdit?delivery_guid=':'http://ck.mingyuanyun.com/#/deliveryEdit?delivery_guid='
angular.module('ContractDredge', [modal])
    .controller('contractDredgeCtrl', [
        '$scope', '$routeParams', 'contractCommonService', 'dregeServer', 'yunkeModal', '$route',
        function ($scope, $routeParams, contractCommonService, dregeServer, yunkeModal, route) {
            const contractId = $routeParams.id;
            //获取合同信息
            contractCommonService.getContract(contractId, function (data) {
                $scope.contractBaseInfo = data.contract;
                $scope.contractApps = data.application;
                $scope.$applyAsync();
            });
            $scope.dredges = {};
            $scope.joint_url = JOINT_URL;
            const removeHmS = str => replace(str, /(\d{4}-\d{1,2}-\d{1,2}).*/, (item, g1) => g1);
            dregeServer.getContractOrganizationInfo(contractId)
                .then(getData)
                .then((data = {}) => {
                    $scope.dredges = data;
                    $scope.dredges.AuthorizeList = chain($scope.dredges.AuthorizeList)
                        .filter(({totalNum}) => totalNum !== 0)
                        .map((item) => ({
                            ...item,
                            settlement_amount: item.SettlementAmount,
                            sign_amount: item.SignAmount,
                            contract_type: item.contract_type,
                            beginOn: removeHmS(item.beginOn),
                            endOn: removeHmS(item.endOn),
                            establishTime: removeHmS(item.establishTime),
                            performanceAccountingTime: removeHmS(item.performanceAccountingTime),
                            OrderCode: item.OrderCode,
                            OrderGUID: item.OrderGUID,
                            settlement_type: item.SettlementType,
                            settlement_scale: item.SettlementScale,
                            discount: item.Discount,
                            rent_period: item.rent_period,
                            authorization_numeric:parseInt(item.authorization_numeric),
                        }))
                        .value()
                })
            dregeServer.getContractSignedReceivableReceived(contractId)
                .then(getData)
                .then(data => {
                    $scope.amountInfo = data
                })
            dregeServer.getContractOrderSummary(contractId)
                .then(getData)
                .then(({summaryAuthorizeList}) => {
                    $scope.summaryAuthorizeList = summaryAuthorizeList
                })
            const doModal = ({title, data, isSpecialContract}) => yunkeModal.open({
                title,
                template: dredgeModal,
                controller: "dredgeModalCtrl",
                resolve: {
                    projectList: dregeServer.getContractOrder(contractId)
                        .then(getData).then(property('sureAuthorizeList')),
                    data: cloneDeep(data),
                    isSpecialContract
                }
            })
            $scope.add = () => {
                doModal({title: '新增授权', isSpecialContract: isSpecial($scope.contractBaseInfo.contract_property_id)})
                    .promise.then(({ApplicationId, beginOn, contract_type, endOn, establishTime, settlement_amount, totalNum, contract_application_id, performanceAccountingTime, OrderCode,area_discount,current_discount,current_real_discount,benchmark_amount,settlement_scale,discount,settlement_type,rent_period,authorization_numeric,sign_amount,income_type_id}) => ({
                    contractId,
                    application_id: ApplicationId,
                    total_num: totalNum,
                    establish_time: establishTime,
                    begin_on: beginOn,
                    end_on: endOn,
                    settlement_amount,
                    contract_type,
                    contract_application_id,
                    performance_accounting_time: performanceAccountingTime,
                    order_code: OrderCode,
                    area_discount,
                    current_discount,
                    current_real_discount,
                    benchmark_amount,
                    settlement_scale,
                    discount,
                    settlement_type,
                    rent_period,
                    authorization_numeric,
                    sign_amount,
                    delivery_rules:false,
                    income_type_id

                }))
                    .then(dregeServer.addContractOrder)
                    .then(route.reload)
            }
            $scope.update = (proj) => {
                doModal({
                    title: '修改授权信息',
                    data: proj,
                    isSpecialContract: isSpecial($scope.contractBaseInfo.contract_property_id)
                })
                    .promise.then(({ApplicationId, Id, establishTime, sign_amount, settlement_amount, beginOn, contract_type, endOn, totalNum, ContractApplicationId, performanceAccountingTime, OrganizationId, OrderCode,area_discount,current_discount,current_real_discount,benchmark_amount,settlement_scale,settlement_type,discount,rent_period,authorization_numeric,delivery_rules}) => ({
                    id: Id,
                    contractId,
                    application_id: ApplicationId,
                    total_num: totalNum,
                    establish_time: establishTime,
                    begin_on: beginOn,
                    end_on: endOn,
                    sign_amount,
                    settlement_amount,
                    contract_type,
                    contract_application_id: ContractApplicationId,
                    organization_id: OrganizationId,
                    performance_accounting_time: performanceAccountingTime,
                    order_code: OrderCode,
                    area_discount,
                    current_discount,
                    current_real_discount,
                    benchmark_amount,
                    settlement_scale,
                    discount,
                    settlement_type,
                    rent_period,
                    authorization_numeric,
                    delivery_rules
                }))
                    .then(dregeServer.addContractOrder)
                    .then(route.reload)
            }
        }])
    .controller('dredgeModalCtrl', ['$scope', 'projectList', 'modalInstance', 'data', 'isSpecialContract','$timeout','$filter', ($scope, projectList, modalInstance, data, isSpecialContract,timeout,$filter) => {
        const now = new Date();
        const dateToDate = function(date){
            let sDate = new Date();
            if (typeof date == 'object'
                && typeof new Date().getMonth == "function"
            ) {
                sDate = date;
            }
            else if (typeof date == "string") {
                let arr = date.split('-')
                if (arr.length == 3) {
                    sDate = new Date(arr[0] + '-' + arr[1] + '-' + arr[2]);
                }
            }
            return sDate;
        }
        const plusMonth = function(date,num){
            num = isNaN(num)?0:num;
            num = parseInt(num);
            var sDate = dateToDate(date);

            var sYear = sDate.getFullYear();
            var sMonth = sDate.getMonth() + 1;
            var sDay = sDate.getDate();

            var eYear = sYear;
            var eMonth = sMonth + num;
            var eDay = sDay;
            while (eMonth > 12) {
                eYear++;
                eMonth -= 12;
            }
            if(isNaN(eMonth)){
                return '';
            }
            var eDate = new Date(eYear, eMonth - 1, eDay);

            while (eDate.getMonth() != eMonth - 1) {
                eDay--;
                eDate = new Date(eYear, eMonth - 1, eDay);
            }
            var nYear = eDate.getFullYear();
            var nMonth = eDate.getMonth()+1;
            var nDay = eDate.getDate();

            var StrDate = '';
            if(nMonth<10){
                StrDate = StrDate + nYear + '-0'+ nMonth;
            }else{
                StrDate = StrDate + nYear + '-' + nMonth;
            }
            if(nDay < 10){
                StrDate  = StrDate + '-0' + nDay;
            }else{
                StrDate  = StrDate + '-' + nDay;
            }
            return StrDate;
        }
        $scope.data = data || {
            establishTime: `${now.getFullYear()}-${now.getMonth() + 1}-${now.getDate()}`,
            performanceAccountingTime: `${now.getFullYear()}-${now.getMonth() + 1}-${now.getDate()}`,
            totalNum: 1,
            current_discount: 100,
            benchmark_sum_amount: 0,
        }
        // 当次优惠折扣
        if($scope.data.current_discount == null || $scope.data.current_discount == ''){
            $scope.data.current_discount = 100;
        }

        $scope.maxAuthorizationNum = $filter('maxAuthorizationNum')($scope.data.authorization_numeric,$scope.data.delivery_rules||false);
        $scope.isSpecialContract = isSpecialContract;
        $scope.isAdd = !$scope.data.ContractId;
        $scope.ddlConfigProjects = {
            allowClear: false,
            data: map(projectList, ({applicationId, applicationName, contract_application_id,area_discount,benchmark_amount,contract_type,rent_period,authorization_numeric,delivery_rules,unit}) => ({
                id: applicationId,
                text: applicationName + '+' + unit,
                contract_application_id,
                area_discount,
                benchmark_amount,
                contract_type,
                rent_period,
                authorization_numeric,
                delivery_rules
            })),
            placeholder: '产品名称',
            onchange2(item) {
                if((!isEmpty(item) && item.contract_application_id == $scope.data.contract_application_id) || $scope.isAdd){
                    $scope.data.contract_application_id = item.contract_application_id;
                    $scope.data.area_discount = item.area_discount;
                    $scope.data.benchmark_amount = item.benchmark_amount;
                    $scope.data.contract_type = parseInt(item.contract_type);
                    $scope.data.rent_period = parseInt(item.rent_period);
                    $scope.data.authorization_numeric = parseInt(item.authorization_numeric);
                    $scope.data.delivery_rules = item.delivery_rules;
                    $scope.maxAuthorizationNum = $filter('maxAuthorizationNum')($scope.data.authorization_numeric,$scope.data.delivery_rules||false);
                    $scope.isAuto = false;
                }else{
                    $scope.isAuto = true;
                }
            }
        };

        $scope.ddlConfigContractType = {
            allowClear: false,
            data: contractType,
            placeholder: '合同属性'
        };

        //结算类型
        $scope.ddlConfigSettlementType = {
            allowClear: false,
            data: settlementType,
            placeholder: '结算类型',
            onchange2(_settlementType) {
                $scope.data.settlement_type = _settlementType.id;
            }
        };

        //禁止修改除已结算金额外所有字段
        // $scope.isAuto = $scope.data.isManual === 2;
        $scope.onResolve = () => modalInstance.resolve($scope.data);
        $scope.onReject = () => modalInstance.reject("关闭")


        function setUp() {
            // TODO 结算基准价：必填，允许修改，自动计算，结算基准单价*授权项目
            $scope.$watch('data.totalNum', function (itemVal) {
                if (parseFloat(itemVal) == 0) {
                    $scope.data.benchmark_sum_amount = 0;
                } else {
                    $scope.data.benchmark_sum_amount = Math.round(myMath.mul(itemVal, $scope.data.benchmark_amount));
                }
            })

            $scope.$watch('data.benchmark_amount', function (itemVal) {
                if (parseFloat(itemVal) == 0) {
                    $scope.data.benchmark_sum_amount = 0;
                } else {
                    $scope.data.benchmark_sum_amount = Math.round(myMath.mul(itemVal, $scope.data.totalNum));
                }

            })

            // TODO 当次实际折扣：自动计算，区域折扣*当次优惠折扣，不允许修改
            $scope.$watch('data.area_discount', function (itemVal) {
                if (parseFloat(itemVal) == 0) {
                    $scope.data.current_real_discount = 0;
                } else {
                    $scope.data.current_real_discount = Math.round(myMath.div(myMath.mul(itemVal, $scope.data.current_discount),100));
                }
            })
            $scope.$watch('data.current_discount', function (itemVal) {
                if (parseFloat(itemVal) == 0) {
                    $scope.data.current_real_discount = 0;
                } else {
                    $scope.data.current_real_discount = Math.round(myMath.div(myMath.mul(itemVal, $scope.data.area_discount),100));
                }
            })

            // TODO 产品是否有租期，有租期的产品，必填，开始时间默认开通时间，结束时间默认开通时间的第二年当天，允许修改
            $scope.$watch('data.performanceAccountingTime', function (itemVal) {
                if($scope.isAdd){
                    if (parseFloat($scope.data.rent_period) == 0) {
                        $scope.data.beginOn = itemVal;
                        $scope.data.endOn = itemVal;
                    }else{
                        $scope.data.beginOn = itemVal;
                        $scope.data.endOn = plusMonth(itemVal,$scope.data.rent_period);
                    }
                }
            })

            $scope.$watch('data.rent_period', function (itemVal) {
                if($scope.isAdd){
                    if (parseInt(itemVal) > 0) {
                        $scope.data.beginOn = $scope.data.performanceAccountingTime;
                        $scope.data.endOn = plusMonth($scope.data.performanceAccountingTime,parseFloat(itemVal));
                    }
                }
            })

        }
        timeout(setUp, 0);
    }])
    .service('dregeServer', ["$http", ($http) => {
        return {
            getContractOrganizationInfo(contractId) {
                return $http.post(`${apiPrefix}/contract/get-contract-organization-info`, {
                    contractId
                })
            },
            getContractSignedReceivableReceived(contractId) {
                return $http.get('/api/index.php?r=/contract/get-contract-signed-receivable-received', {
                    params: {
                        contractId
                    }
                })
            },
            getContractOrder(contractId) {
                return $http.get('/api/index.php?r=/contract/get-contract-order', {
                    params: {
                        contractId
                    }
                })
            },
            getContractOrderSummary(contractId) {
                return $http.get('/api/index.php?r=/contract/get-contract-order-summary', {
                    params: {
                        contractId
                    }
                })
            },
            addContractOrder({application_id, sign_amount, total_num, establish_time, begin_on, end_on, settlement_amount, contract_num, contract_type, id, contractId, contract_application_id, performance_accounting_time, organization_id, order_code,area_discount,current_discount,current_real_discount,benchmark_amount,settlement_scale,discount,settlement_type}) {
                return $http.post('/api/index.php?r=/contract/add-contract-order', {
                    application_id,
                    total_num,
                    establish_time,
                    begin_on,
                    end_on,
                    sign_amount,
                    settlement_amount,
                    contract_num,
                    contract_type,
                    id,
                    contractId,
                    contract_application_id,
                    performance_accounting_time,
                    organization_id,
                    order_code,
                    area_discount,
                    current_discount,
                    current_real_discount,
                    benchmark_amount,
                    settlement_scale,
                    discount,
                    settlement_type
                }).success(function (json) {
                    if (json.retCode == 0 && json.errMsg != "") {
                        util.alert(json.errMsg);
                    }
                }).error(function () {
                    util.alert('服务器内部错误');
                });

            }
        }
    }])
    .filter('productTypeFormat', () => (id) => {
        const table = {
            1: "新增",
            2: "增购",
            3: "续签"
        }
        return id ? table[id] : id
    })
    .filter('maxAuthorizationNum', () => (max,rules) => {
        if(rules == 2 || rules == 3){
            return 1;
        }
        return max ? parseInt(max):0;
    })
